<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="评标任务" prop="taskId">
        <el-select v-model="queryParams.taskId" placeholder="请选择评标任务" clearable size="small">
          <el-option
            v-for="item in taskList"
            :key="item.id"
            :label="item.taskName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="工程类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择工程分类" clearable size="small">
          <el-option v-for="sort in sortList" :key="sort.id" :label="sort.name" :value="sort.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="供应商" prop="sortId">
        <el-select v-model="queryParams.companyId" placeholder="请选择供应商" clearable size="small">
          <el-option
            v-for="item in companyList"
            :key="item.id"
            :label="item.companyName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['tender:project:add']"
        >导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="showExport"
          v-hasPermi="['tender:sort:export']"
        >导出</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" show-overflow-tooltip width="50px" />
      <el-table-column label="评标任务名称" align="center" width="200" prop="taskName" />
      <el-table-column label="工程类型" align="center" prop="typeName" />
      <el-table-column label="工程编号" align="center" prop="projectNo" width="150" />
      <el-table-column label="项目名称" align="center" prop="projectName" width="200" />
      <el-table-column label="项目特征" align="center" prop="projectFeature" width="400" />
      <el-table-column label="计量单位" align="center" prop="projectMeasure" />
      <el-table-column label="工程量" align="center" prop="projectTotal" />
      <el-table-column label="创建人" align="center" prop="userName" />
      <el-table-column label="创建时间" align="center" prop="creatorDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creatorDate) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工程项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      导入工程项目清单文件：支持格式excl
      请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="评标任务" prop="taskId">
          <el-select v-model="form.taskId" placeholder="请选择评标任务" clearable size="small">
            <el-option
              v-for="item in taskList"
              :key="item.id"
              :label="item.taskName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="工程类型" prop="sortType">
          <el-select v-model="form.sortType" placeholder="请选择工程分类" clearable size="small">
            <el-option v-for="sort in sortList" :key="sort.id" :label="sort.name" :value="sort.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="工程清单">
          <el-upload
            class="upload-demo"
            :action="'/dev-api/newUploadFile/upload'"
            :on-success="fileUploadSuccess"
            multiple
            :before-upload="beforeAvatarUpload"
            :show-file-list="false"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
          
        </el-form-item>
        <el-form-item>
      <el-button type="primary"  icon="el-icon-download"  v-show="downloadFlag"  @click="handleExportError">错误文档下载</el-button>
        </el-form-item>
<!-- 
        <el-table :data="appendixList" style="width: 100%;">
          <el-table-column
            show-overflow-tooltip
            prop="fileName"
            label="附件名称"
            align="center"
            min-width="100"
          >
            <template slot-scope="scope" @click="showAppendix(scope.row)">
              <el-button type="text">{{scope.row.uploadName}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="150">
            <template slot-scope="scope">
              <el-button type="text" @click="showAppendix(scope.row)">查看</el-button>
              <el-button
                type="text"
                @click="deleteAppendix(scope.row)"
                class="fontRed"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


<el-dialog :title="title" :visible.sync="downOpen" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="评标任务1" prop="taskId">
          <el-select v-model="form.taskId" placeholder="请选择评标任务" clearable size="small">
            <el-option
              v-for="item in taskList"
              :key="item.id"
              :label="item.taskName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工程类型" prop="sortType">
          <el-select v-model="form.sortType" placeholder="请选择工程分类" clearable size="small">
            <el-option v-for="sort in sortList" :key="sort.id" :label="sort.name" :value="sort.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
           <el-button icon="el-icon-download"   type="warning"  @click="handleExportError">确认下载</el-button>
          </el-form-item>
      </el-form>
    </el-dialog>


  </div>
</template>

<script>
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  exportProject,
  listTaskInfo,
  listSortType,
  getCompanyList,
  upload,
  reservePrice
} from "@/api/tender/project";
import { uploadUrl ,deleteOneAppendix ,downloadFile,formatTimeToStr} from "@/api/tender/common";
export default {
  name: "Project",
  data() {
    return {
      downloadFlag:false,
      downFileName:'',
      downFilePath:'',
      // 遮罩层
      loading: true,
      downOpen:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 工程项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: undefined,
        typeId: undefined,
        projectNo: undefined,
        projectName: undefined,
        projectFeature: undefined,
        projectMeasure: undefined,
        projectTotal: undefined,
        price: undefined,
        totalPrice: undefined,
        reseverPrice: undefined,
        avePrice: undefined,
        creatorId: undefined,
        creatorDate: undefined
      },
      // 表单参数
      form: {},
      appendixList: [],
      // 表单校验
      rules: {},
      companyList: [],
      sortList: [],
      taskList: []
    };
  },
  created() {
    this.getList();
    this.getSortList();
    this.getCompanyList();
    this.getTaskList();
  },
  methods: {
   
    /** 查询工程项目列表 */
    getList() {
      this.loading = true;
      this.queryParams.type = 1;
      listProject(this.queryParams).then(response => {
        if (response.code === "ok") {
          this.projectList = response.data.data.list;
          this.total = response.data.data.total;
          this.loading = false;
        } else {
          this.projectList = [];
          this.total = 0;
          this.loading = false;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        taskId: undefined,
        typeId: undefined,
        projectNo: undefined,
        projectName: undefined,
        projectFeature: undefined,
        projectMeasure: undefined,
        projectTotal: undefined,
        price: undefined,
        totalPrice: undefined,
        reseverPrice: undefined,
        avePrice: undefined,
        creatorId: undefined,
        creatorDate: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.downloadFlag = false;
      this.title = "添加工程项目";
    },

/** 
 * 打开excel下载对话框
 */
 showExport(){
        this.downOpen = true;
         this.title = "下载工程清单";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
       this.downloadFlag = false;
      const id = row.id || this.ids;
      getProject(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工程项目";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateProject(this.form).then(response => {
              if (response.code === "ok") {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.data.msg);
              }
            });
          } else {
            addProject(this.form).then(response => {
              if (response.code === "ok") {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.data.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除工程项目编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delProject(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    //工程分类
    getSortList() {
      const params = { type: 1 };
      listSortType(params).then(response => {
        this.sortList = response.data.data;
      });
    },
    // 供应商列表信息
    getCompanyList() {
      getCompanyList().then(response => {
        this.companyList = response.data.data;
      });
    },
    //任务列表
    getTaskList() {
      listTaskInfo().then(response => {
        this.taskList = response.data.data;
      });
    },

    //文件上传之前的验证
    beforeAvatarUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10 MB！");
      }
      if(!this.form.taskId){
          this.$message.error("请选择招标任务。");
          return false;
      }
       if(!this.form.sortType){
          this.$message.error("请选择工程类型。");
          return false;
      }
      return isLt10M;
    },
    //弹出框附件上传成功回调函数
    fileUploadSuccess(res) {
      if (res.data.code ==="0") {
        this.form.type = 1;
        this.form.filePath = res.data.data.filePath;
        this.appendixList.push(res.data.data);
        upload(this.form).then(res=>{
           if(res.data.code==="0"){
            this.open = false;
            this.getList();
             this.$message.success("上传成功");
           }else{
            this.$message.error(res.data.msg);
            this.downloadFlag = true;
            this.downFileName = res.data.data.fileName;
            this.downFilePath = res.data.data.filePath;
           }
        });
      } else {
        this.$message.error("文件上传服务器出问题了！");
      }
    },
    //预览附件
    showAppendix(data) {
      if (this.appendixList && this.appendixList.length < 1) {
        this.$message.warning("没有要查看的附件");
        return;
      }
      findFileUrls(this.appendixList, data);
    }
,
        //基本资料-删除附件
        deleteAppendix(data) {
            this.$confirm("确实删除该附件吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                center: true
            }).then(() => {
                deleteOneAppendix({
                    filePath: data.filePath
                }).then(res => {
                    if (res.data.code !== '0') return this.$message.error('删除失败')
                    this.$message.success('删除成功')
                    this.appendixList.forEach((item, i) => {
                        if (item.filePath == data.filePath) {
                            this.appendixList.splice(i, 1)
                        }
                    })
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            })

        },
        //下载错误文档信息
        handleExportError(){
          const fo = new Object();
          fo.name = this.downFileName;
          fo.filepath = this.downFilePath;
           downloadFile(fo).then(res=>{
               var blob=res;
               var url = window.URL.createObjectURL(blob);
               //blob.type = "application/excel";
               var a = document.createElement('a');
              　a.href = url;
              　a.download = 'test.xlsx';
              　a.click();
              window.URL.revokeObjectURL(url);
           });
        }
  }
};
</script>